<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, watch, onMounted, reactive, computed } from 'vue'
import { TUser } from '@/Types/user'
import { getClassnameListService } from '@/api/education/classname'
import { getClassListByUserIdService } from '@/api/user_classname'
import type { FormInstance, FormRules } from 'element-plus'

// 班级相关类型定义
interface ClassInfo {
	classId: number
	level: string
	academy: string
	major: string
	grade: number
	classname: number
}

// 初始化表单
const formRef = ref<FormInstance>()
const userDialogLoading = ref(false)
const form = ref<TUser>({
	userId: '',
	uname: '',
	userTypeId: '',
	classId: ''
})

// 原始用户数据（用于比较是否有变化）
const originalForm = ref<TUser>({})

// 班级列表
const classList = ref<ClassInfo[]>([])

// 用户当前所属班级列表
const userClassList = ref<any[]>([])

// 选中的班级ID数组
const selectedClassIds = ref<number[]>([])

// 用户类型选项
const userTypeOptions = [
	{ value: 1, label: '学生' },
	{ value: 2, label: '任课老师' },
	{ value: 3, label: '辅导员' },
	{ value: 4, label: '管理员' }
]

// 表单验证规则
const rules = reactive<FormRules>({
	userTypeId: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
})

// 接收父组件数据
const props = defineProps<{
	dialogVisible: boolean
	userData: TUser
}>()

// 向父组件传递数据
const emit = defineEmits<{
	closeDialog: [value: boolean]
	updateUser: [userData: TUser]
}>()

// 监听对话框显示状态
watch(
	() => props.dialogVisible,
	(newVal) => {
		if (newVal && props.userData) {
			// 对话框打开时，设置表单数据
			form.value = { ...props.userData }
			originalForm.value = { ...props.userData }
			selectedClassIds.value = []
			getUserClassInfo()
		}
	}
)

// 检查是否有数据变化
const hasChanges = computed(() => {
	return (
		form.value.userTypeId !== originalForm.value.userTypeId ||
		JSON.stringify(selectedClassIds.value.sort()) !==
			JSON.stringify((originalForm.value.classIdList || []).sort())
	)
})

// 获取用户当前所属班级信息
const getUserClassInfo = async () => {
	if (!form.value.userId) return

	try {
		const res = await getClassListByUserIdService(Number(form.value.userId))
		if (res.data.code === 1) {
			userClassList.value = res.data.data
			// 设置当前选中的班级ID数组
			selectedClassIds.value = res.data.data.map((item: any) => item.classId)
		}
	} catch (error) {
		console.error('获取用户班级信息失败:', error)
	}
}

// 获取班级列表并排序
const getClassList = async () => {
	try {
		const res = await getClassnameListService()
		if (res.data.code === 1) {
			// 对班级列表进行排序
			classList.value = res.data.data.sort((a: ClassInfo, b: ClassInfo) => {
				// 1. 按学历层次排序（本科在前，专科在后）
				if (a.level !== b.level) {
					return a.level === 'undergrad' ? -1 : 1
				}
				// 2. 按学院名称排序
				if (a.academy !== b.academy) {
					return a.academy.localeCompare(b.academy)
				}
				// 3. 按专业排序
				if (a.major !== b.major) {
					return a.major.localeCompare(b.major)
				}
				// 4. 按年级从小到大排序
				if (a.grade !== b.grade) {
					return a.grade - b.grade
				}
				// 5. 按班级号从小到大排序
				return a.classname - b.classname
			})
		}
	} catch (error) {
		ElMessage.error('获取班级列表失败')
	}
}

// 格式化班级显示文本
const formatClassLabel = (classInfo: ClassInfo) => {
	if (!classInfo) return ''
	const levelText = classInfo.level === 'undergrad' ? '本科' : '专科'
	return `${levelText}-${classInfo.academy}-${classInfo.major}-${classInfo.grade}级-${classInfo.classname}班`
}

// 关闭对话框
const closeDialog = () => {
	emit('closeDialog', false)
}

// 提交表单
const submitForm = async () => {
	if (!formRef.value) return

	await formRef.value.validate(async (valid: boolean) => {
		if (!valid) return

		// 检查是否有变化
		if (!hasChanges.value) {
			ElMessage.info('没有数据变化')
			return
		}

		userDialogLoading.value = true

		try {
			// 准备要更新的数据
			const updateData: TUser = {
				userId: form.value.userId,
				userTypeId: form.value.userTypeId
			}

			// 如果班级有变化，添加班级信息
			if (
				JSON.stringify(selectedClassIds.value.sort()) !==
				JSON.stringify((originalForm.value.classIdList || []).sort())
			) {
				updateData.classIdList = selectedClassIds.value
			}

			emit('updateUser', updateData)
		} catch (error) {
			console.error('更新用户失败:', error)
			ElMessage.error('更新用户失败')
		} finally {
			userDialogLoading.value = false
		}
	})
}

// 重置表单
const resetForm = () => {
	if (formRef.value) {
		formRef.value.resetFields()
	}
	form.value = { ...originalForm.value }
	selectedClassIds.value = originalForm.value.classIdList ? [...originalForm.value.classIdList] : []
}

// 生命周期
onMounted(() => {
	getClassList()
})

// 暴露方法给父组件
defineExpose({
	resetForm
})
</script>

<template>
	<el-dialog
		:model-value="props.dialogVisible"
		@close="closeDialog"
		title="编辑用户"
		width="600px"
		:close-on-click-modal="false"
	>
		<div class="dialog-content" v-loading="userDialogLoading">
			<el-form
				ref="formRef"
				:model="form"
				:rules="rules"
				class="form-container"
				label-position="right"
				label-width="100px"
			>
				<el-form-item label="用户ID">
					<el-input v-model="form.userId" disabled />
				</el-form-item>

				<el-form-item label="姓名">
					<el-input v-model="form.uname" disabled />
				</el-form-item>

				<el-form-item prop="userTypeId" label="用户类型">
					<el-select v-model="form.userTypeId" placeholder="请选择用户类型" style="width: 100%">
						<el-option
							v-for="option in userTypeOptions"
							:key="option.value"
							:label="option.label"
							:value="option.value"
						/>
					</el-select>
				</el-form-item>

				<el-form-item label="所属班级">
					<el-select
						v-model="selectedClassIds"
						placeholder="请选择班级"
						style="width: 100%"
						clearable
						filterable
						multiple
					>
						<el-option
							v-for="classInfo in classList"
							:key="classInfo.classId"
							:label="formatClassLabel(classInfo)"
							:value="classInfo.classId"
						/>
					</el-select>
				</el-form-item>

				<!-- 显示用户当前班级信息（只读） -->
				<el-form-item label="当前班级" v-if="userClassList.length > 0">
					<div class="current-class-info">
						<el-tag
							v-for="classInfo in userClassList"
							:key="classInfo.classId"
							type="info"
							style="margin-right: 8px; margin-bottom: 8px"
						>
							{{ formatClassLabel(classInfo) }}
						</el-tag>
					</div>
				</el-form-item>
			</el-form>
		</div>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="resetForm">重置</el-button>
				<el-button @click="closeDialog">取消</el-button>
				<el-button type="primary" @click="submitForm" :disabled="!hasChanges">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<style lang="scss" scoped>
.dialog-content {
	padding: 20px 0;
}

.form-container {
	.el-form-item {
		margin-bottom: 24px;
	}
}

.current-class-info {
	padding: 8px 12px;
	background-color: var(--el-fill-color-light);
	border-radius: 4px;
	min-height: 40px;
	display: flex;
	align-items: center;
	flex-wrap: wrap;
}

.dialog-footer {
	.el-button {
		margin-left: 10px;
	}
}
</style>
